package com.rybbaby.tss.platform.sysAdminUser.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.enums.MemberPropertyEnum;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssStudent.entity.ViewTssStudent;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import com.rybbaby.tss.platform.sysAdminUserJoinSysRole.entity.SysAdminUserJoinSysRole;
import com.rybbaby.tss.platform.sysAdminUserJoinSysRole.service.ISysAdminUserJoinSysRoleService;
import com.rybbaby.tss.platform.sysRole.entity.SysRole;
import com.rybbaby.tss.platform.sysRole.service.ISysRoleService;
import com.rybbaby.tss.platform.sysRoleGroup.entity.SysRoleGroup;
import com.rybbaby.tss.platform.sysRoleGroup.service.ISysRoleGroupService;
import com.rybbaby.tss.platform.sysSchool.entity.SysSchool;
import com.rybbaby.tss.platform.sysSchool.service.ISysSchoolService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 谢进伟
 * @description 管理员基本信息管理
 * @createDate 2016-11-22 下午1:36:42
 */
@Controller
@RequestMapping(value = "sysAdminUserController")
public class SysAdminUserController extends BaseController {

    @Autowired
    private ISysAdminUserJoinSysRoleService sysAdminUserJoinSysRoleService;
    @Autowired
    private ISysRoleGroupService sysRoleGroupService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;
    @Autowired
    private ISysSchoolService sysSchoolService;

    /**
     * 获取管理员基本信息列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取管理员基本信息列表", save = true)
    @RequestMapping(value = "sysAdminUserList", method = RequestMethod.POST)
    public ModelAndView sysAdminUserList(SysAdminUser entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysAdminUserListView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysAdminUser.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            String ids = "";
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            if (sysAdminUser.getUserName().equals("admin")) {
            } else {
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" id in ('" + ids + "') "));
            }
            dc.addOrder(Order.desc("lastUpdateTime"));
            PageBean pageBean = sysAdminUserService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param targetDateId 接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到管理员基本信息视图", save = true)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) String serializeNum, Boolean sign) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysAdminUserEditView"));
        List<SysRole> schoolRoleList = new ArrayList<>();
        List<SysAdminUserJoinSysRole> roleList = new ArrayList<>();
        // 角色名称数据源
        if (StringUtils.isNotBlank(targetDateId)) {
            SysAdminUser editEntity = this.sysAdminUserService.get(targetDateId);
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
            // 查询该用户拥有的角色
            schoolRoleList = getSchoolRoles( editEntity);

            SysRoleGroup sysRoleGroup = this.sysRoleGroupService.findUniqueByProperty("code", editEntity.getSchoolId());
            if (sysRoleGroup != null) {
                DetachedCriteria dc = DetachedCriteria.forClass(SysAdminUserJoinSysRole.class);
                dc.add(Restrictions.eq("adminUserId", editEntity.getId()));
                roleList = this.sysAdminUserJoinSysRoleService.findByDetached(dc);
            }
            if (sign != null && sign == true) {
                mav.addObject("sign", true);
            }
        } else {
            mav.addObject("editModel", "add");
        }
        mav.addObject("schoolRoleList", schoolRoleList);
        mav.addObject("rolesList", roleList);

        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存管理员基本信息对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(SysAdminUser entity, String roleIds, String roleIds_old) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            StringBuffer delteFileIds = new StringBuffer();
            String id = entity.getId();
            // 新上传的文件映射:格式：groupName=>headPortrait
            String headPortrait = getParameter("newHeadPortrait");
            // 字段headPortrait被删除历史文件id,格式：id1,id2,id3...idn
            String deleteHeadPortrait = getParameter("deleteHeadPortrait");
            delteFileIds.append(deleteHeadPortrait);
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                SysAdminUser destEntity = this.sysAdminUserService.get(id);
                String newPassword = entity.getUserPassword();
                if (StringUtils.isNotBlank(newPassword) && !newPassword.equals(destEntity.getUserPassword())) {
                    // 密码加密
                    if (StringUtils.isNotBlank(entity.getUserPassword())) {
                        SysAdminUser tempUser = new SysAdminUser();
                        tempUser.setId(destEntity.getId());
                        tempUser.setCreateTime(destEntity.getCreateTime());
                        tempUser.setUserPassword(entity.getUserPassword());
                        String encryptPassword = encryptPassword(tempUser);
                        entity.setUserPassword(encryptPassword);
                    }
                }
                BeanUtils.copyProperties(entity, destEntity, "createTime","version","isForbidden","isCanDelete","isOpenAccount","adminUserCode");
                destEntity.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
                this.sysAdminUserService.updateEntitiy(destEntity, getSession().getId(), getLoginUserId() + "", delteFileIds.toString(), headPortrait);
                // 保存用户角色
                Object loginUserId_obj = getLoginUserId();
                if (StringUtils.isNotBlank(roleIds) && !roleIds.equals(roleIds_old)) {
                    if (StringUtils.isNotBlank(roleIds_old)) {
                        String sql = "delete from   sys_admin_user_join_sys_role  where adminUserId = ?";
                        List params = new LinkedList<Object>();
                        String userId = destEntity.getId();
                        params.add(userId);
                        sysAdminUserJoinSysRoleService.executeSql(sql, params.toArray());
                    }
                    String[] arr = roleIds.split(",");
                    if (arr != null && arr.length > 0) {
                        for (int i = 0; i < arr.length; i++) {
                            SysAdminUserJoinSysRole role = new SysAdminUserJoinSysRole();
                            role.setRoleId(arr[i]);
                            role.setAdminUserId(destEntity.getId());
                            role.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            role.setCreateUserId(loginUserId_obj == null ? null : loginUserId_obj.toString());
                            role.setId(getSession().getId());
                            this.sysAdminUserJoinSysRoleService.save(role);
                        }
                    }
                }
            } else {
                entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                Object loginUserId_obj = getLoginUserId();
                entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                entity.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
                entity.setCreateUser(loginUserId_obj == null ? null : loginUserId_obj.toString());
                entity.setIsForbidden(false);
                entity.setIsOpenAccount(false);
                entity.setIsCanDelete(true);

                //生成员工编码
                //获取园所码
                SysSchool sysSchool=this.sysSchoolService.get(entity.getSchoolId());
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("sequenceName", "SEQUENCE_TSS_SYS_ADMIN_USER_CONTRACT_CODE");
                paramsMap.put("schoolCode",sysSchool.getSchoolCode());
                paramsMap.put("memberProperty", MemberPropertyEnum.员工.value());
                String resultCode = CodeGenUtil.getCodeGen(paramsMap);
                Gson gson = new Gson();
                Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
                }.getType());
                if(Double.parseDouble(map.get("resCode")+"")==200){
                    entity.setAdminUserCode(map.get("data").toString());
                }
                Serializable newId = this.sysAdminUserService.save(entity, getSession().getId(), getLoginUserId() + "", headPortrait);
                if (newId == null) {
                    ajr.setResCode(301);
                    ajr.setResMsg("保存失败!");
                } else {
                    // 密码加密,用jdbc查询防止缓存
                    String sql = "SELECT createTime FROM sys_admin_user WHERE id=?";
                    Map<String, Object> newstMatp = this.sysAdminUserService.findOneForJdbc(sql, new Object[]{newId});
                    Object createTime = newstMatp.get("createTime");
                    if (createTime != null && createTime instanceof Timestamp) {
                        entity.setCreateTime(Timestamp.valueOf(createTime.toString()));
                    }
                   /* if (StringUtils.isNotBlank(entity.getUserPassword())) {
                        String encryptPassword = encryptPassword(entity);
                        entity.setUserPassword(encryptPassword);
                        this.sysAdminUserService.updateEntitiy(entity);
                    }
                    // 保存用户角色
                    if (StringUtils.isNotBlank(roleIds)) {
                        String[] arr = roleIds.split(",");
                        if (arr != null && arr.length > 0) {
                            for (int i = 0; i < arr.length; i++) {
                                SysAdminUserJoinSysRole role = new SysAdminUserJoinSysRole();
                                role.setRoleId(arr[i]);
                                role.setAdminUserId(newId + "");
                                role.setCreateTime(new Timestamp(System.currentTimeMillis()));
                                role.setCreateUserId(loginUserId_obj == null ? null : loginUserId_obj.toString());
                                role.setId(getSession().getId());
                                this.sysAdminUserJoinSysRoleService.save(role);
                            }
                        }
                    }*/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 转到开通账户视图
     *
     * @param targetDataId 转到开通账户视图
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到开通账户视图", save = true)
    @RequestMapping(value = "toOpenAccountView", method = RequestMethod.GET)
    public ModelAndView toOpenAccountView(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String targetDataId, Boolean sign) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysAdminUseOpenAccountView"));
        List<SysRole> roleList = new ArrayList<>();
        // 角色名称数据源
        if (StringUtils.isNotBlank(targetDataId)) {
            SysAdminUser editEntity = this.sysAdminUserService.get(targetDataId);
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
            roleList = getSchoolRoles( editEntity);
            if (sign != null && sign == true) {
                mav.addObject("sign", true);
            }
        } else {
            mav.addObject("editModel", "add");
        }
        mav.addObject("rolesList", roleList);
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("openAccountUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOpenAccount.do");
        return mav;
    }

    /**
     * 获取指定员工所在园所的所有角色
     * @param editEntity
     * @return
     */
    private List<SysRole> getSchoolRoles( SysAdminUser editEntity) {
        List<SysRole> roleList=new ArrayList<>();
        // 查询该用户拥有的角色
        SysRoleGroup sysRoleGroup = this.sysRoleGroupService.findUniqueByProperty("code", editEntity.getSchoolId());
        if (sysRoleGroup != null) {
            DetachedCriteria dc = DetachedCriteria.forClass(SysRole.class);
            dc.add(Restrictions.eq("groupId", sysRoleGroup.getId()));
            roleList = this.sysRoleService.findByDetached(dc);
        }
        return roleList;
    }


    /**
     * 转到重置密码界面
     *
     * @param targetDataId 转到重置密码界面
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到开通账户视图", save = true)
    @RequestMapping(value = "toResetPassWordView", method = RequestMethod.GET)
    public ModelAndView toResetPassWordView(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String targetDataId) {

        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("resetAdminUserPasswordView"));
        SysAdminUser editEntity = this.sysAdminUserService.get(targetDataId);
        mav.addObject("editEntity", editEntity);
        return mav;
    }


    /**
     * 保存开通权限
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存开通权限", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOpenAccount", method = RequestMethod.POST)
    public String openAccount(SysAdminUser entity, String roleIds, String roleIds_old) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            StringBuffer delteFileIds = new StringBuffer();
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                SysAdminUser destEntity = this.sysAdminUserService.get(id);
                String newPassword = entity.getUserPassword();
                if(StringUtils.isBlank(newPassword)){
                    newPassword="qzy123456";
                }
                SysAdminUser tempUser = new SysAdminUser();
                tempUser.setId(destEntity.getId());
                tempUser.setCreateTime(destEntity.getCreateTime());
                tempUser.setUserPassword(newPassword);
                String encryptPassword = encryptPassword(tempUser);

                entity.setUserPassword(encryptPassword);
                entity.setIsForbidden(false);
                entity.setIsCanDelete(true);
                entity.setIsOpenAccount(true);
                BeanUtils.copyProperties(entity, destEntity, "createTime", "version", "schoolId","isForbidden","isCanDelete");
                destEntity.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
                this.sysAdminUserService.updateEntitiy(destEntity, getSession().getId(), getLoginUserId() + "", delteFileIds.toString());
                // 保存用户角色
                Object loginUserId_obj = getLoginUserId();
                if (StringUtils.isNotBlank(roleIds) && !roleIds.equals(roleIds_old)) {
                    if (StringUtils.isNotBlank(roleIds_old)) {
                        String sql = "delete from   sys_admin_user_join_sys_role  where adminUserId = ?";
                        List params = new LinkedList<Object>();
                        String userId = destEntity.getId();
                        params.add(userId);
                        sysAdminUserJoinSysRoleService.executeSql(sql, params.toArray());
                    }
                    String[] arr = roleIds.split(",");
                    if (arr != null && arr.length > 0) {
                        for (int i = 0; i < arr.length; i++) {
                            SysAdminUserJoinSysRole role = new SysAdminUserJoinSysRole();
                            role.setRoleId(arr[i]);
                            role.setAdminUserId(destEntity.getId());
                            role.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            role.setCreateUserId(loginUserId_obj == null ? null : loginUserId_obj.toString());
                            role.setId(getSession().getId());
                            this.sysAdminUserJoinSysRoleService.save(role);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                SysAdminUser sysAdminUser = this.sysAdminUserService.get(id);
                if (sysAdminUser != null && !sysAdminUser.getIsCanDelete()) {
                    ajr.setResMsg("该用户不允许删除!");
                    ajr.setResCode(302);
                } else {
                    if ("40280981582deed501582dfc94a40000".equals(sysAdminUser.getId())) {// 超级管理员Id
                        ajr.setResMsg("无权无法删除删除该用户(提示：\"是否删除\"选项对该用户无效)!");
                        ajr.setResCode(302);
                    } else {
                        this.sysAdminUserService.deleteEntityById(id);
                    }
                }
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                if (ids.contains("40280981582deed501582dfc94a40000")) {// 超级管理员Id
                    ajr.setResMsg("包含了无权无法删除删除的超级管理员用户(提示：\"是否删除\"选项对超级管理员户无效)!");
                    ajr.setResCode(302);
                } else {
                    boolean isIncludeNotDeleteData = false;
                    String sql = "SELECT COUNT(1) count FROM sys_admin_user WHERE id IN('" + StringUtils.join(ids.split(","), "','") + "') AND isCanDelete = 0";
                    Map<String, Object> map = this.sysAdminUserService.findOneForJdbc(sql, null);
                    if (map != null) {
                        Object count = map.get("count");
                        if (count != null && Integer.parseInt(count.toString()) > 0) {
                            isIncludeNotDeleteData = true;
                            ajr.setResMsg("删除失败(包含不可删除的记录)!");
                            ajr.setResCode(302);
                        }
                    }
                    if (!isIncludeNotDeleteData) {
                        boolean batchDelete = this.sysAdminUserService.batchDelete(ids.split(","));
                        if (!batchDelete) {
                            ajr.setResMsg("删除失败!");
                            ajr.setResCode(302);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 转到编辑视图
     *
     * @return
     */
    @RequestLog(content = "转到登录用户基本信息视图", save = true)
    @RequestMapping(value = "LoginEditView", method = RequestMethod.GET)
    public ModelAndView LoginEditView() {
        Object loginUserId = getLoginUserId();
        SysAdminUser editEntity = this.sysAdminUserService.get(loginUserId.toString());
        return toEditView(loginUserId.toString(), SequenceUtil.getUpperCaseUUID(), true);
    }

    /**
     * 验证用户名
     *
     * @param userName 用户名
     * @return
     */
    @ResponseBody
    @RequestLog(content = "验证用户名", save = true)
    @RequestMapping(value = "verificationUserName", method = RequestMethod.POST)
    public String verificationUserName(String userName, String id, String schoolAccount, String educationalAccount) {
        try {
            Map<String, Object> findOneForJdbc = new HashMap<>();
            StringBuffer sql = new StringBuffer();
            if (StringUtils.isNotBlank(userName)) {
                sql.append(" SELECT COUNT(1) count FROM sys_admin_user WHERE userName = ? ");
                if (id != null && id != "") {
                    sql.append("AND id != '" + id + "'");
                }
                findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{userName});
            } else if (StringUtils.isNotBlank(schoolAccount)) {
                sql.append(" SELECT COUNT(1) count FROM sys_admin_user WHERE userName = ? ");
                if (id != null && id != "") {
                    sql.append("AND id != '" + id + "'");
                }
                findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{schoolAccount});
            } else if (StringUtils.isNotBlank(educationalAccount)) {
                sql.append(" SELECT COUNT(1) count FROM sys_admin_user WHERE userName = ? ");
                if (id != null && id != "") {
                    sql.append("AND id != '" + id + "'");
                }
                findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{educationalAccount});
            }
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重置密码
     *
     * @param oldPassword     旧密码
     * @param newPassword     新密码
     * @param confirmPassowrd 确认新密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "resetPassword")
    public String resetPassword(@RequestParam(required = false) String oldPassword, @RequestParam(required = true) String newPassword, @RequestParam(required = true) String confirmPassowrd,@RequestParam(required = false) String targetDataId) {
        int resCode = 200;
        String resMsg = "修改成功";
        Object loginUserId = super.getLoginUserId();
        String password="";
        String newEncryPassword="";
        if (StringUtils.isNotBlank(loginUserId)) {
            SysAdminUser loginUser = this.sysAdminUserService.get(loginUserId.toString());
            if (loginUser != null) {
                if (StringUtils.isNotBlank(oldPassword)) {
                    password = EncryptPasswordUtil.encryptAdminPassword(loginUserId.toString(), loginUser.getCreateTime(), oldPassword);
                     newEncryPassword = EncryptPasswordUtil.encryptAdminPassword(loginUserId.toString(), loginUser.getCreateTime(), newPassword);
                    if (!password.equals(loginUser.getUserPassword())) {
                        resCode = -1;
                        resMsg = "旧密码错误,重置密码失败!";
                    } else {
                        if (!oldPassword.equals(newPassword)) {
                            if (newPassword.equals(confirmPassowrd)) {
                                loginUser.setUserPassword(newEncryPassword);
                                this.sysAdminUserService.updateEntitiy(loginUser);
                                super.cacheLoginUsr(loginUser, null);
                            } else {
                                resCode = -1;
                                resMsg = "新密码和确认密码不一致，修改失败!";
                            }
                        } else {
                            resCode = -1;
                            resMsg = "新密码不能与旧密码一样，修改失败!";
                        }
                    }
                } else if(StringUtils.isNotBlank(targetDataId)&&StringUtils.isBlank(oldPassword)) {
                    SysAdminUser adminUser=this.sysAdminUserService.get(targetDataId);
                    password = EncryptPasswordUtil.encryptAdminPassword(adminUser.toString(), adminUser.getCreateTime(), oldPassword);
                    newEncryPassword = EncryptPasswordUtil.encryptAdminPassword(adminUser.getId(), adminUser.getCreateTime(), newPassword);
                    if (!newEncryPassword.equals(password)) {
                        if (newPassword.equals(confirmPassowrd)) {
                            adminUser.setUserPassword(newEncryPassword);
                            this.sysAdminUserService.updateEntitiy(loginUser);
                           // super.cacheLoginUsr(adminUser, null);
                        } else {
                            resCode = -1;
                            resMsg = "新密码和确认密码不一致，修改失败!";
                        }
                    } else {
                        resCode = -1;
                        resMsg = "新密码不能与旧密码一样，修改失败!";
                    }
                }
            } else {
                resCode = -1;
                resMsg = "修改失败(管理员不存在)!";
            }
        } else {
            resCode = -1;
            resMsg = "修改失败(未登录系统)!";
        }
        return new AjaxJsonResponse(resMsg, resCode).jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "停用启用员工对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "updateIsForbidden", method = RequestMethod.POST)
    public String updateIsForbidden(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) Boolean isForbidden) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            Integer status = this.sysAdminUserService.updateIsForbidden(targetDateId, isForbidden);
            if (status == null) {
                ajr.setResMsg("操作失败!");
                ajr.setResCode(302);
            } else {
                ajr.setResMsg("操作成功!");
                ajr.setResCode(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("操作失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(true);
    }


    /**
     * 基础设置>员工设置模块导出
     * 杨然
     * 2017年11月9日16:57:49
     */

    @RequestLog(content = "导出", save = true)
    @Token(validateToken = false)
    @ResponseBody
    @RequestMapping("/exportExcle")
    public void exportExcle(Integer flag, String ids, HttpServletResponse response, HttpServletRequest request) {
        System.out.println(ids);
        List<SysAdminUser> staffList = null;
        String path = "jso/export_staff.json";
        String templateName = request.getParameter("templateName");
        if (ids == "") {
            staffList = this.sysAdminUserService.getAllList();
        } else {
            staffList = this.sysAdminUserService.findListByIds(Arrays.asList(ids.split(",")));
        }
        ExportUtil u = new ExportUtil();
        u.export(path, templateName, staffList, request, response);
    }

    /**
     * 根据职务查询员工信息
     *
     * @param entity
     * @param duty
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据职务查询员工信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getPostListByDuty", method = RequestMethod.POST)
    public String tssPostListByDuty(SysAdminUser entity, @RequestParam(required = true) Integer duty) throws Exception {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();
            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);

            List<SysAdminUser> tssStaffList = this.sysAdminUserService.getPostListByDuty(duty, sysAdminUser.getSchoolId());
            ajr.setData(tssStaffList.toArray());
        } catch (Exception e) {
            throw e;
        }
        return ajr.jsonResponse(true);
    }


    /**
     * 验证手机号
     *
     * @param schoolId 手机号
     * @return
     */
    @ResponseBody
    @RequestLog(content = "验证手机号", save = true)
    @RequestMapping(value = "verificationPhone", method = RequestMethod.POST)
    public String verificationPhone(String schoolId, String phoneNumber, String id) {
        try {
            //String phoneNumber=request.getParameter("phoneNumber");
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT COUNT(1) count FROM sys_admin_user WHERE phoneNUmber = ? and schoolId= ?");
            if (id != null && id != "") {
                sql.append(" AND id != '" + id + "'");
            }
            Map<String, Object> findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{phoneNumber, schoolId});
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
